<template>
    <el-dialog
                :title="percenCenterTitle"
                :visible.sync="dialogFormVisible"
                :show-close="false"
                @closed="initChangeInfo"
                id="person-center"
        >
        <el-dialog
                width="30%"
                title="重新绑定手机号"
                @close="initPhoneInfo"
                :visible.sync="innerVisible"
                append-to-body>
            <el-form :model="phoneForm" :rules="Prules" ref="phoneForm" label-width="100px" class="phonecheck">
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="phoneForm.phone"
                              placeholder="请输入新手机号码"
                              @input="checkPhone"
                              autofocus="true">
                    </el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <el-input v-model="phoneForm.checkMa"
                              placeholder="请输入手机验证码"
                              autofocus="true">
                    </el-input>
                    <el-button round type="primary" size="mini" class="checkMa" :disabled="canuse" @click="getCheckMa"><span v-if="time == 0 ">获取验证码</span><span v-else>{{time}}秒后重新获取</span></el-button>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="innerVisible = false">取 消</el-button>
                <el-button type="primary" @click="checkCheckMa()">确定</el-button>
            </div>
        </el-dialog>
            <div class="header">
                <p>当前账号：{{currentAccount}}</p>
                <el-button-group>
                    <el-button
                            type="primary"
                            size="mini"
                            plain
                            @click="showinfo=1"
                            :class="showinfo == 1? 'focus' : ''"
                    >信息</el-button>
                    <el-button
                            type="primary"
                            size="mini"
                            plain
                            @click="showinfo=2"
                            :class="showinfo == 2? 'focus' : ''"
                    >密码</el-button>
                </el-button-group>
            </div>
            <section class="infosec" v-show="showinfo == 1">
                <div class="infoLeft">
                    <p>头像：</p>
                    <div style="display: flex; align-items: center">
                        <img :src="imageUrl" class="avatar" @click="handlePictureCardPreview">
                        <el-upload
                                class="avatar-uploader"
                                ref="upload"
                                :action="uploadURL"
                                :headers="headers"
                                :show-file-list="false"
                                :auto-upload="false"
                                :before-upload="beforeAvatarUpload"
                                :on-error="handleError"
                                :on-change="handleAvatarChange"
                                :on-success="handleAvatarSuccess"
                        >
                            <el-button size="small" type="primary">更换头像</el-button>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible" append-to-body>
                            <img width="100%" :src="imageUrl" alt="">
                        </el-dialog>
                    </div>

                    <div class="setting" style="margin-top: 10px;">
                        <p>以下信息由管理员设置</p>
                        <ul>
                            <!--<li style="width: 100%; overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">公司：{{list.company}}</li>-->
                            <li>公司：{{list.company}}</li>
                            <li>部门：{{list.apartment}}</li>
                            <li>职位：{{list.position}}</li>
                        </ul>
                    </div>
                </div>
                <el-form
                        :model="ruleForm"
                        ref="ruleForm"
                        :rules="rules"
                        status-icon
                        label-width="100px"
                        class="demo-ruleForm"
                >
                    <el-form-item label="姓名" prop="name" :rules="rules.nameRules">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-radio-group v-model="ruleForm.sex">
                            <el-radio :label="0">男</el-radio>
                            <el-radio :label="1">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="年龄" :rules="rules.ageRules" prop="age">
                        <el-input v-model="ruleForm.age"></el-input>
                    </el-form-item>
                    <el-form-item prop="email" label="邮箱" :rules="rules.emailRules">
                        <el-input v-model="ruleForm.email" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <!--<el-input type="age" v-model.number="ruleForm.phone" autocomplete="off"></el-input>-->
                        <div style="display: flex; justify-content: space-between">
                            <p style="margin-left: 10px;">{{ruleForm.phone}}</p>
                            <el-button type="text" @click="innerVisible = true">重新绑定</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </section>
            <section class="pwdsec" v-show="showinfo == 2">
                <el-form
                        :model="pwd"
                        ref="ruleForm2"
                        status-icon
                        label-width="100px"
                        class="demo-ruleForm"
                        :rules="rules1"
                >
                    <el-form-item label="原始密码" prop="pass" :rules="rules1.pwdrules">
                        <el-input type="password" v-model="pwd.pass" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="checkPass" :rules="rules1.pwdrules">
                        <el-input type="password" v-model="pwd.checkPass" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="重复新密码" prop="confirmPass" :rules="rules1.confirmpwdrules">
                        <el-input type="password" v-model="pwd.confirmPass" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </section>
            <div slot="footer" class="dialog-footer" v-show="showinfo == 1">
                <el-button @click="showfalse">取 消</el-button>
                <el-button type="primary" @click="saveInfo()">保 存</el-button>
            </div>
            <div slot="footer" class="dialog-footer" v-show="showinfo == 2">
                <el-button @click="showfalse">取 消</el-button>
                <el-button type="primary" @click="upatePwd">确认修改</el-button>
            </div>
        </el-dialog>
</template>
<script>
  import { mapMutations, mapState } from "vuex";
  export default {
    name:"PersonCenter",
    props:["dialogFormVisible","imageUrl","ruleForm","list"],
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"));
        } else if (value !== this.pwd.checkPass) {
          callback(new Error("两次输入密码不一致!"));
        } else {
          callback();
        }
      };
      return {
        canuse:true,
        time:0,
        timer:null,
        phoneForm: {
          phone:"",
          checkMa:""
        },
        innerVisible:false,
        pwd: {
          pass: "",
          checkPass: "",
          confirmPass: ""
        },
        rules1:{
          pwdrules: [
            { required: true, message: "密码不能为空" },
            { pattern: /^.{6,}$/, message: "密码长度大于6位" }
          ],
          confirmpwdrules: [
            { required: true, message: "密码不能为空" },
            { pattern: /^.{6,}$/, message: "密码长度大于6位" },
            { validator: validatePass, trigger: "blur" }
          ],
        },
        Prules:{
          phone: [
            {
              pattern: /^[1][3,4,5,7,8][0-9]{9}$/,
              message: "手机号不正确",
              trigger: "blur"
            }
          ]
        },
        rules: {
          nameRules: [
            {
              pattern: /^[^\\\/:.*?\"<>| ]+$/,
              message: "命名不符合规则",
              trigger: "blur"
            }
          ],
          ageRules: [
            {
              pattern: /^(?:[1-9]?\d|100)$/,
              message: "年龄在0~100岁之间",
              trigger: "blur"
            }
          ],
          emailRules: []
        },
        currentAccount: JSON.parse(localStorage.getItem("userInfo")).userEmail,
        showinfo: 1,
        headers: { authToken: localStorage.getItem("authToken") },
        uploadURL: this.$BaseUrl + "/user/updateHeadImg",
        percenCenterTitle: "修改信息",
        dialogVisible: false
      };
    },
    created() {
    },
    mounted() {},
    watch: {
      showinfo: {
        handler: function(newVal, oldVal) {
          if (newVal == 1) {
            this.percenCenterTitle = "修改信息";
          } else {
            this.percenCenterTitle = "修改密码";
          }
        }
      }
    },
    methods: {
      checkCheckMa(){
        this.$http.post("/sms/checkSmsCode",{
          code:this.phoneForm.checkMa,
          phone:this.phoneForm.phone
        }).then(res=>{
          let {data} = res;
          console.log(res);
          if(res.status == 200){
            this.$message({
              type:"success",
              message:"新手机号验证成功"
            })
            this.innerVisible = false;
            this.ruleForm.phone = this.phoneForm.phone;
          }else{
            this.$message.error(res.msg);
          }
        })
      },
      checkPhone(){
        this.canuse = true;
        this.$refs.phoneForm.validate((valid) => {
          if (valid) {
            this.canuse = false
            this.$http.post("/company/checkPhone", {
              userPhone: this.phoneForm.phone
            }).then(res => {
              console.log(res);
              if (res.status == 200) {
                if (res.data == 1) {
                  this.canuse = true;
                  this.$message.error(res.msg);
                  return;
                } else {
                  this.canuse = false;
                }
              }
            })
          }
        })
      },
      getCheckMa(){
        this.$http.post("/sms/sendSmsCode",{
          phone:this.phoneForm.phone
        }).then(res=>{
          console.log(res);
          if(res.status == 200){
            this.time = 60;
            this.timer = setInterval(()=>{
              this.canuse = true;
              this.time--;
              if(this.time == 0){
                this.canuse = false;
                clearInterval(this.timer)
              }
            },1000)
            if(res.data == 1){
              this.$message.error(res.msg);
            }
          }
        })
      },
      handlePictureCardPreview() {
        this.dialogVisible = true;
      },
      mapLoction(arr) {
        var newArr = [];
        arr.forEach(function (oldData, i) {
          var index = -1;
          var alreadyExists = newArr.some(function (newData, j) {
            if (oldData.id === newData.id) {
              index = j;
              return true;
            }
          });
          if (!alreadyExists) {
            newArr.push({
              id: oldData.id,
              res: [{
                "value": oldData.value
              }]
            });
          } else {
            newArr[index].res.push({
              "value": oldData.value
            });
          }
        });
        return newArr;
      },
      showfalse(){
        this.$emit("changeDialogFormVisible",false);
      },
      initPhoneInfo(){
        this.$refs["phoneForm"].resetFields();
        this.phoneForm.checkMa = "";
        this.time = 0;
        clearInterval(this.timer);
        this.canuse = true;
      },
      initChangeInfo() {
        this.$refs["ruleForm"].resetFields();
        this.$refs.ruleForm.resetFields();
        this.$refs.ruleForm2.resetFields();
        this.imgurl = "";
        this.showinfo = 1;
        this.$emit("dialogClosed");
      },
      beforeAvatarUpload(file) {
        return true;
      },
      handleAvatarSuccess(res, file) {
        console.log("handleAvatarSuccess", file);
        this.imgUrl = URL.createObjectURL(file.raw);
        this.uploadFile = file;
        this.$emit("changeImage",this.imgUrl);
        localStorage.setItem("loginImg", this.imgUrl);
      },
      handleError(res, file) {
        console.log("handleError", res, file);
      },
      handleAvatarChange(file) {
        console.log("aaaaaaaaaaa", file);
        let file1 = file.raw;
        const isJPG = file1.type === "image/jpeg";
        const isGIF = file1.type === "image/gif";
        const isPNG = file1.type === "image/png";
        const isBMP = file1.type === "image/bmp";
        const isLt2M = file1.size / 1024 / 1024 < 2;
        if ((isJPG || isGIF || isPNG || isBMP) && isLt2M) {
            this.$emit("changeheadimg",URL.createObjectURL(file.raw))
        }
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error("上传图片必须是JPG/GIF/PNG/BMP 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
      },
      saveInfo() {
        this.$refs.ruleForm.validate((valid) =>{
            if(valid){
              this.$emit("changeDialogFormVisible",false);
              this.$refs.upload.submit();
              this.$http
                .post("/user/updateOwn", {
                  age: this.ruleForm.age,
                  sex: this.ruleForm.sex,
                  realName: this.ruleForm.name,
                  userPhone: this.ruleForm.phone
                })
                .then(res => {
                  if (res.status == 200) {
                    this.$message({
                      message:"保存成功",
                      type:"success"
                    });
                    this.$emit("changeuserName",this.ruleForm.name);
                    localStorage.setItem('realName',this.ruleForm.name)
                    this.$emit("changeheadimg",1);
                  } else {
                    this.$message.error(res.msg);
                  }
                });
            }
        })

      },
      upatePwd() {
        if (
          this.pwd.pass != "" &&
          this.pwd.checkPass != "" &&
          this.pwd.confirmPass != ""
        ) {
          if (this.pwd.checkPass != this.pwd.confirmPass) {
            return;
          } else {
            this.$refs.ruleForm2.validate((valid) => {
              if (valid) {
                this.$http
                  .post("/user/updatePassword", {
                    oldPwd: this.pwd.pass,
                    newPwd: this.pwd.checkPass
                  })
                  .then(res => {
                    if (res.status == 200) {
                      this.$message(res.msg);
                      this.$emit("changeDialogFormVisible",false);
                    } else {
                      this.$message.error(res.msg);
                    }
                  });
              }
            })
          }
        }
      },
    }
  };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss">
    .phonecheck{
        .el-form-item__content{
            margin-left: 0!important;
            display: flex;
            .checkMa{
                margin-left: 10px;
                font-size: 14px;
            }
        }
        .el-form-item__label{
            width: 55px!important;
        }
    }
</style>
<style scoped lang="scss">
    @import "scss_vars";
    #person-center{
        .header {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #d9ecff;
            height: 40px;
            .el-button-group {
                height: 30px;
                display: flex;
                justify-content: center;
                width: 50%;
            }
            .focus {
                background: #409eff!important;
                border-color: #409eff!important;
                color: #fff!important;
            }
        }
    }
    .pwdsec {
        height: 310px;
        margin-top: 20px;
        border-bottom: 1px solid #d9ecff;
    }
    .infosec {
        height: 310px;
        margin-top: 20px;
        border-bottom: 1px solid #d9ecff;
        display: flex;
        .infoLeft {
            width: 40%;
            padding: 0 30px;
            .setting {
                color: #909399;
                p {
                    margin-bottom: 10px;
                }
                li {
                    color: #333;
                    line-height: 30px;
                    /*width: 100%;*/
                    min-width: 230px;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }
            }
        }
        .el-form {
            padding: 0 30px;
            width: 60%;
        }
        .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
            width: 100%;
        }
        .avatar-uploader-icon {
            display: flex;
            flex-direction: column;
            justify-content: center;
            font-size: 28px;
            color: #8c939d;
            width: 120px;
            height: 120px;
            text-align: center;
        }
        .avatar-uploader {
            margin-left: 20px;
        }
        .avatar {
            width: 120px;
            height: 120px;
            display: block;
            border: 1px dashed #c0ccda;
        }
        .avatar:hover {
            border: 1px dashed #1989fa;
        }
    }
</style>
